#include "replay_Center.h"
#include "ui_replay_Center.h"
static  char  speedString[9][8]={"1/16","1/8","1/4","1/2","1","2","4","8","16"};
static  float speedfloat[9]{1.0/16,1.0/8,1.0/4,1.0/2,1.0,2.0,4.0,8.0,16.0};
static int  speedInt[9]={116,108,104,102,1,2,4,8,16};

#define desktop_width QApplication::desktop()->width()
#define desktop_height QApplication::desktop()->height()

replayCenter *replayCenter::m_instance = 0;

replayCenter::replayCenter(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::replayCenter)
{
    ui->setupUi(this);
    replay_initData();
    replay_initUI();
    replay_initConnect();
}
void replayCenter::mousePressEvent(QMouseEvent*event)
{
    if(event->buttons()==Qt::RightButton){
        PRTLOG()<<"close replay";
        if(m_rplyStaus == Rply_Playing){
            playback_stop();
            m_Replay_StartTime.clear();
            sleep_ms(200);
        }
        emit reply_exitSignal();   //界面透明点击鼠标右键相当于点击录像回放界面
    }else if(event->buttons()==Qt::LeftButton){
       PRTLOG()<<"pos:"<<QCursor::pos();
    }
}

replayCenter::~replayCenter()
{
    delete ui;
}
void replayCenter::replay_initUI(){
    ///ProcessBar UI Init
    this->resize(desktop_width,desktop_height);
    this->setAttribute(Qt::WA_TranslucentBackground,true);
    this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
    ui->playback_process_tbW->setMouseTracking(true);
    ui->playback_process_tbW->installEventFilter(this);
    this->setFixedWidth(desktop_width);
    ui->playback_process_tbW->setFixedHeight(60);
    ui->playback_process_tbW->setSelectionMode(QAbstractItemView::NoSelection);
    ui->playback_process_tbW->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->playback_process_tbW->verticalHeader()->setSectionsClickable(false);
    ui->playback_process_tbW->horizontalHeader()->setVisible(false);
    ui->playback_process_tbW->horizontalHeader()->setStretchLastSection(false);
    ui->playback_process_tbW->verticalHeader()->setVisible(false); //隐藏列表头

    ///Calender UI Init
    QStringList ch_list;
    for(int i=0;i<4;i++){
        ch_list.append(QString::number(i+1));
    }
    ui->ReplaySwitch_cBx1_1->blockSignals(true);
    ui->ReplaySwitch_cBx1_1->addItems(ch_list);
    ui->ReplaySwitch_cBx1_1->blockSignals(false);

}
void replayCenter::replay_initData(){
    m_rplyProcessTcpSrv = new QTcpServer(this);
    m_rplyProcessTcpSrv->listen(QHostAddress::AnyIPv4,8091);

    m_tbW_EmptyRowNum=(m_tbW_DataRowNum<=1)?0:m_tbW_DataRowNum;
    m_tbW_row = m_tbW_TimeRowNum+m_tbW_DataRowNum+m_tbW_EmptyRowNum;
    m_Replay_StartTime = QString("00:00:00");
    for(int i=0;i<MAX_REPLAY_WIN_NUM;i++){
        m_replayTimerCtl[i].speed = Rply_Speed_1;
        m_replayTimerCtl[i].current_Cell = 0;
        m_replayTimerCtl[i].status = Rply_Stop;
    }
    m_rplyIndex=0;

    m_MouseTimer.setInterval(1000);
    m_MouseTimer.start();
}

void replayCenter::replay_initConnect(){
    connect(&m_ctrlTimer_Timing,SIGNAL(timeout()),this,SLOT(ctrlTimertimeout_slot()));
    connect(this,SIGNAL(httpReq_signal(bool,QString,QString,int,QJsonObject)),g_httpClient.httpHandler,SLOT(http_Post_Sender(bool,QString,QString,int,QJsonObject)),Qt::QueuedConnection);
    connect(g_httpClient.httpHandler,SIGNAL(http_reply(QString,QJsonDocument)),this,SLOT(httpRply_slots(QString,QJsonDocument)),Qt::QueuedConnection);
    connect(m_rplyProcessTcpSrv,SIGNAL(newConnection()),this,SLOT(rply_processNotifyTcp_slot()));
    connect(&m_MouseTimer,SIGNAL(timeout()),this,SLOT(mouseTimertimeout_slot()));
}
void replayCenter::mouseTimertimeout_slot()
{
    if(m_MouseIn_col  != m_MouseTmp_col)
        m_MouseIn_col = m_MouseTmp_col;
    else{
        if(m_MousMove){
            m_MousMove= false;
            this->update();
        }
    }
}

void replayCenter::replay_initProcessTbW(){
    m_smlCellNum_InbigCell = (m_tbW_width/pbrZoom_24H)/CELL_COLUMN_WIDTH;
    m_smlCell_seconds = (m_bigCell_seconds*1.0)/m_smlCellNum_InbigCell;
    m_tbW_col = (int)(m_smlCellNum_InbigCell*m_pbrZoom);

    ui->playback_process_tbW->setRowCount(m_tbW_row);
    ui->playback_process_tbW->setColumnCount(m_tbW_col);
    for(int col=0;col<m_tbW_col;col++){
       ui->playback_process_tbW->setColumnWidth(col,CELL_COLUMN_WIDTH);
    }
    for(int row=0;row<m_tbW_row;row++){
        if(row == 0){
            ui->playback_process_tbW->setRowHeight(row,DATA_ROW_HEIGHT);
            m_tbW_height+=DATA_ROW_HEIGHT;
        }else{
            if(row%2==1){
                ui->playback_process_tbW->setRowHeight(row,DATA_ROW_HEIGHT);
                m_tbW_height+=DATA_ROW_HEIGHT;
            }else{
                ui->playback_process_tbW->setRowHeight(row,EMPTY_ROW_HEIGHT);
                m_tbW_height+=EMPTY_ROW_HEIGHT;
            }
        }
    }
    m_tbW_height += m_tbW_height_deault;
    ui->playback_process_tbW->setFixedHeight(m_tbW_height);
    for(int col=0;col<m_tbW_col;col++){
       for(int row=0;row<m_tbW_row;row++){
           QTableWidgetItem *item = new QTableWidgetItem();
           if(row==0){
               item->setBackground(QBrush(ROW_HGAP_BACKCOLOR));
               item->setSelected(false);
           }else{
               if(row%2){
                   ///Data
                   item->setBackground(QBrush(ROW_NORECORD_BACKCOLOR));
                   if(col%m_smlCellNum_InbigCell==0 && col != 0){
                       item->setBackground(QBrush(ROW_VGAP_BACKCOLOR));///
                   }
               }else{
                   //Empty
                   item->setBackground(QBrush(ROW_HGAP_BACKCOLOR));
               }

           }
           ui->playback_process_tbW->setItem(row,col,item);
       }
    }
    ui->playback_process_tbW->setSpan(0,0,1,m_tbW_col);
    if(m_timeLinePainter != NULL){
        m_timeLinePainter->deleteLater();
        m_timeLinePainter = NULL;
    }else{
        m_timeLinePainter = new TimePainter(this);
        m_timeLinePainter->TimePaint_setPara(m_smlCellNum_InbigCell,m_bigCell_seconds);
        ui->playback_process_tbW->setCellWidget(0,0,m_timeLinePainter);//放置时间刻度轴
    }
}

void replayCenter::on_playback_process_tbW_cellEntered(int row, int column)
{
    m_MouseTmp_col = column;
    m_MousMove= true;
}

void replayCenter::paintEvent(QPaintEvent *){

    int col_x=QCursor::pos().x();
    int cuTime_x=10+ (ui->playback_process_tbW->pos().x())+col_x;
    int cuTime_y= ui->title_frame->y() + ui->title_frame->height()+m_MouseTimeOffset;
    QPainter painter(this);
    painter.setPen(Qt::yellow);
    painter.setRenderHint(QPainter::Antialiasing, true);
    if(cuTime_x >= m_tbW_width*9/10){
        cuTime_x -=50;
    }
    int sc=(m_MouseIn_col*1.0)/(m_smlCellNum_InbigCell*m_pbrZoom)*24*3600;
    int ch=sc/3600;
    int cm = (sc%3600)/60;
    int cs = (sc%3600)%60;
    char ctims[16]={'\0'};sprintf(ctims,"%02d:%02d:%02d",ch,cm,cs);
    painter.drawText(QPoint(cuTime_x,cuTime_y), QString(ctims));///get the mouse's pos time
}


///Paint the RecordData to the TableWidget
void  replayCenter::replay_drawRecordData(REC_Type type ,char * stime,char * etime,QBrush recColor){
    recordCellInfo recordCell;
    int sy,smon,sd,sh,smin,ss;
    int ey,emon,ed,eh,emin,es;
    sscanf(stime,"%04d-%02d-%02d %02d:%02d:%02d",&sy,&smon,&sd,&sh,&smin,&ss);
    sscanf(etime,"%04d-%02d-%02d %02d:%02d:%02d",&ey,&emon,&ed,&eh,&emin,&es);

    int st_0 =  abs(sh*3600+smin*60+ss);
    int et_0 = abs(eh*3600+emin*60+es);

    recordCell.startCell = static_cast<int>(st_0/m_smlCell_seconds);
    recordCell.endCell = static_cast<int>(et_0/m_smlCell_seconds);
    switch(type){
        case REC_TIMING:m_RecordInfoArray[m_rplyIndex].timing_rCList.append(recordCell);break;
        case REC_ALARM:m_RecordInfoArray[m_rplyIndex].alarm_rCList.append(recordCell);break;
        default:m_RecordInfoArray[m_rplyIndex].timing_rCList.append(recordCell);break;
    }
    for(int i=recordCell.startCell;i<=recordCell.endCell;i++){
        QTableWidgetItem *item = ui->playback_process_tbW->item(m_tbW_TimeRowNum,i);
        if(i%m_smlCellNum_InbigCell==0 && i != 0){
            item->setBackground(QBrush(ROW_NORECORD_BACKCOLOR));///
        }else{

            item->setBackground(recColor);
        }

    }
    this->update();
}



void replayCenter::replay_rePaint_ByRECType(REC_Type type){
    QList <h_records>       tmp_rTList;
    QList <recordCellInfo>  tmp_rCList;
    QBrush recColor;
    switch (type){
        case REC_TIMING:{
            recColor=QBrush(ROW_TIMING_DATA_BACKCOLOR);
            recordListInfoCpy(&tmp_rTList,m_RecordInfoArray[m_rplyIndex].timing_rTList);
            recordCellInfoCpy(&tmp_rCList,m_RecordInfoArray[m_rplyIndex].timing_rCList);
            break;
        }
        case REC_ALARM:{
            recColor=QBrush(ROW_ALARM_DATA_BACKCOLOR);
            recordListInfoCpy(&tmp_rTList,m_RecordInfoArray[m_rplyIndex].alarm_rTList);
            recordCellInfoCpy(&tmp_rCList,m_RecordInfoArray[m_rplyIndex].alarm_rCList);
            break;
        }
        default:{
            recColor=QBrush(ROW_TIMING_DATA_BACKCOLOR);
            recordListInfoCpy(&tmp_rTList,m_RecordInfoArray[m_rplyIndex].timing_rTList);
            recordCellInfoCpy(&tmp_rCList,m_RecordInfoArray[m_rplyIndex].timing_rCList);
            break;
        }
    }
    for(int i=0;i<tmp_rTList.count();i++){
        h_records r=tmp_rTList.at(i);
        replay_drawRecordData(type,r.startTime,r.endTime,recColor);
    }///Timing
}

















void replayCenter::playback_ZoomX_24H(){
    m_pbrZoom=pbrZoom_24H;
    m_bigCell_seconds = 3600;
}
void replayCenter::playback_ZoomX_12H(){
    m_pbrZoom=pbrZoom_6H;///Length x2   24x2
    m_bigCell_seconds = 900;

}
void replayCenter::playback_ZoomX_2H(){
    m_pbrZoom=pbrZoom_1M;
    m_bigCell_seconds = 60;
}
void replayCenter::playback_ZoomX_4H(){
    m_pbrZoom=pbrZoom_1H;
    m_bigCell_seconds = 300;
}
void replayCenter::playback_show(){
    sleep_ms(2500);
    this->show();
    m_tbW_height=0;
    if(m_timeLinePainter != NULL){
        m_timeLinePainter->deleteLater();
        m_timeLinePainter = NULL;
    }
    ui->playback_process_tbW->clear();
    m_tbW_width =ui->playback_process_tbW->width();
    switch(m_pbrZoom){
        case pbrZoom_24H:playback_ZoomX_24H();break;
        case pbrZoom_6H:playback_ZoomX_12H();break;
        case pbrZoom_1H:playback_ZoomX_4H();break;
        case pbrZoom_1M:playback_ZoomX_2H();break;
        default:playback_ZoomX_24H();break;
    }
    if(pbrZoom_24H==24)
        m_scrolBarHeight=0;
    else
        m_scrolBarHeight=20;
    this->replay_initProcessTbW();
    replay_rePaint_CurrentData();
    replay_startQuery();
}



void replayCenter::playback_hide(){
    m_replayRecordQuery=false;
    this->hide();
}
void replayCenter::on_playbackCtl_Zoom24H_pBt_clicked()
{
    m_pbrZoom = pbrZoom_24H;
    playback_show();
}

void replayCenter::on_playbackCtl_Zoom12H_pBt_clicked()
{
    m_pbrZoom = pbrZoom_6H;
    playback_show();
}

void replayCenter::on_playbackCtl_Zoom4H_pBt_clicked()
{

    m_pbrZoom = pbrZoom_1H;
    playback_show();
}

void replayCenter::on_playbackCtl_Zoom2H_pBt_clicked()
{
    m_pbrZoom = pbrZoom_1M;
    playback_show();
}

void replayCenter::on_playback_process_tbW_doubleClicked(const QModelIndex &index)
{
    ui->playback_process_tbW->item(index.row(),index.column())->setSelected(false);
    replay_selectTimeToReplay(index.column());
}

void replayCenter::ctrlTimertimeout_slot(){
    m_ctrTimer_timeOutTimes++;
    QColor nextColColor;
    if((--m_alarmSpeed)<=0){
        m_alarmTimes -= m_alarmStep;
        playback_initAlarmPara();
    }
    if(ui->playbackCtl_smart_cBx->checkState() == Qt::Checked && m_alarmTimes <= 0){
        ///PLAY next alarm Video
        int cellPos=m_replayTimerCtl[m_rplyIndex].current_Cell;
        QTableWidgetItem *old_stem = ui->playback_process_tbW->item(m_Replay_Row,cellPos-1);
        QTableWidgetItem *new_stem = ui->playback_process_tbW->item(m_Replay_Row,cellPos);
        if(cellPos%m_smlCellNum_InbigCell !=0 && cellPos != 0){
            if(ui->playbackCtl_smart_cBx->checkState() == Qt::Checked)
                old_stem->setBackground(QBrush(ROW_ALARM_DATA_BACKCOLOR));
            new_stem->setBackground(QBrush(ROW_ALARM_DATA_BACKCOLOR));
            m_replayTimerCtl[m_rplyIndex].current_Cell++;
        }
        m_replayTimerCtl[m_rplyIndex].current_Cell++;
        replay_selectTimeToReplay(m_replayTimerCtl[m_rplyIndex].current_Cell);
    }


    /////update the process widget


    if(m_ctrTimer_timeOutTimes >= m_ctrTimer_Interval/1000){
        m_ctrTimer_timeOutTimes=0;
        QTableWidgetItem *prev_stem =NULL;
        QTableWidgetItem *next_stem =NULL;
        for(int i=0;i<MAX_REPLAY_WIN_NUM;i++){
            if(m_replayTimerCtl[i].status == Rply_Playing){
                int cuCell=1+m_replayTimerCtl[i].current_Cell;
                QList <recordCellInfo> recList;
                recordCellInfoCpy(&recList,m_RecordInfoArray[m_rplyIndex].timing_rCList);
                for(int i=0;i<recList.count()-1;i++){
                    recordCellInfo block1 = recList.at(i);
                    recordCellInfo block2 = recList.at(i+1);
                    if(cuCell <= block1.startCell){
                        ///change record
                        cuCell = block1.startCell;
                        break;
                    }else if(cuCell >= block1.startCell && cuCell <= block1.endCell){
                        if(cuCell%m_smlCellNum_InbigCell ==0){
                            cuCell++;
                            prev_stem = ui->playback_process_tbW->item(m_Replay_Row,cuCell-2);
                        }else{
                            prev_stem = ui->playback_process_tbW->item(m_Replay_Row,cuCell-1);
                        }
                        prev_stem->setBackground(QBrush(m_originalColBackColor));
                        ///change record
                        next_stem = ui->playback_process_tbW->item(m_Replay_Row,cuCell);
                        m_originalColBackColor = next_stem->backgroundColor();

                        break;
                    }else if(cuCell >= block1.endCell && cuCell <= block2.startCell){
                        if(cuCell%m_smlCellNum_InbigCell ==0){
                            cuCell++;
                            prev_stem = ui->playback_process_tbW->item(m_Replay_Row,cuCell-2);
                            prev_stem->setBackground(QBrush(ROW_VGAP_BACKCOLOR));
                        }else{
                            prev_stem = ui->playback_process_tbW->item(m_Replay_Row,cuCell-1);
                            prev_stem->setBackground(QBrush(m_originalColBackColor));
                        }
                        ///change record
                        cuCell = block2.startCell;

                        next_stem = ui->playback_process_tbW->item(m_Replay_Row,cuCell);
                        m_originalColBackColor = next_stem->backgroundColor();
                        break;
                    }else if(cuCell >= block2.startCell && cuCell <= block2.endCell){
                        if(cuCell%m_smlCellNum_InbigCell ==0){
                            cuCell++;
                            prev_stem = ui->playback_process_tbW->item(m_Replay_Row,cuCell-2);
                            prev_stem->setBackground(QBrush(ROW_VGAP_BACKCOLOR));
                        }else{
                            prev_stem = ui->playback_process_tbW->item(m_Replay_Row,cuCell-1);
                            prev_stem->setBackground(QBrush(m_originalColBackColor));
                        }
                        ///change record
                        next_stem = ui->playback_process_tbW->item(m_Replay_Row,cuCell);
                        m_originalColBackColor = next_stem->backgroundColor();
                        break;
                    }else{
                        continue;
                    }
                }
                m_replayTimerCtl[i].current_Cell = cuCell;
            }
        }
        int cellPos=m_replayTimerCtl[m_rplyIndex].current_Cell;
        QTableWidgetItem *new_stem = ui->playback_process_tbW->item(m_Replay_Row,cellPos);
        nextColColor =new_stem->backgroundColor();
        QTableWidgetItem *old_stem = ui->playback_process_tbW->item(m_Replay_Row,cellPos-1);
        old_stem->setBackground(QBrush(m_originalColBackColor));
        m_originalColBackColor = nextColColor;
        new_stem->setBackground(QBrush(RPLY_CUCOL_BACKCOLOR));


        if(m_ctrTimer_Interval<60000 ){///1m
            m_queryProcess_Times--;
            if(m_queryProcess_Times <=0){
                replay_IamAlive();
                m_queryProcess_Times=3;
            }
        }else{
            replay_IamAlive();
        }
    }
}

void  replayCenter::playback_stop(){
    PRTLOG()<<"Stop playback"<<m_Replay_StartTime.toLocal8Bit().data();
    QJsonObject postData;
    postData["userID"] = QString::number(OnlineUserInfo.userID);
    postData["reqType"] = QString("POST");
    postData["channel"] = m_rply_ch;///query---Ch
    postData["outch"] = m_rply_outch;///
    postData["command"] =QString("STOP");
    m_replayCtl=true;
    m_rplyStaus = Rply_Stop;
    emit httpReq_signal(g_httpClient.httpsEnable,g_httpClient.http_srvIP,QString("/playback/replay/guiSetup"),g_httpClient.httpPort,postData);
    m_RplySpeed = Rply_Speed_1;
    ui->playbackCtl_SpeedInfo_lbl->setText(QString("x %1").arg(speedString[m_RplySpeed]));
}
void  replayCenter::playback_Pause(){


}
void  replayCenter::playback_Play(int ch,int outch){
    QJsonObject postData;
    m_rply_ch = ch;
    m_rply_outch = outch;
    postData["userID"] = QString::number(OnlineUserInfo.userID);
    postData["reqType"] = QString("POST");
    postData["channel"] = ch;///query---Ch
    postData["outch"] = outch;///
    postData["command"] =QString("START");
    postData["StartTime"] =m_Replay_StartTime;
    postData["EndTime"] =m_Replay_EndTime;
    PRTLOG()<<"Start Replay"<<m_Replay_StartTime<<m_Replay_EndTime;
    m_replayCtl=true;
    m_rplyStaus = Rply_Playing;
    emit httpReq_signal(g_httpClient.httpsEnable,g_httpClient.http_srvIP,QString("/playback/replay/guiSetup"),g_httpClient.httpPort,postData);
    m_ctrTimer_Interval = static_cast<int>(m_smlCell_seconds*1000/speedfloat[m_RplySpeed]);
    replay_timerRestart();
}




void  replayCenter::replay_selectTimeToReplay(int col){
    int s_Col=col;
    ///select the ch's record data
    switch(m_replay_totalChs){
        case 1:{m_rplyIndex =0;break;}
        case 4:{m_rplyIndex =0;break;}
        case 9:{m_rplyIndex =0;break;}
        case 16:{m_rplyIndex =0;break;}
    }
    if(m_rplyStaus == Rply_Playing){
        playback_stop();
        m_Replay_StartTime.clear();
        sleep_ms(200);
    }
    QList <recordCellInfo> recList;
    QList <h_records> recTimeList;
    if(ui->playbackCtl_smart_cBx->isChecked()){
        recordCellInfoCpy(&recList,m_RecordInfoArray[m_rplyIndex].alarm_rCList);
        recordListInfoCpy(&recTimeList,m_RecordInfoArray[m_rplyIndex].alarm_rTList);
    }else{
        recordCellInfoCpy(&recList,m_RecordInfoArray[m_rplyIndex].timing_rCList);
        recordListInfoCpy(&recTimeList,m_RecordInfoArray[m_rplyIndex].timing_rTList);
    }
    for(int i=0;i<(recList.count()>recTimeList.count()?recTimeList.count():recList.count());i++){
        recordCellInfo block = recList.at(i);
        h_records      recInfo = recTimeList.at(i);
        QDateTime sdt,edt;
        if(s_Col >= block.startCell && s_Col <= block.endCell){
            s_Col = s_Col;
            sdt= QDateTime::fromString(recInfo.startTime,"yyyy-MM-dd hh:mm:ss");
            edt= QDateTime::fromString(recInfo.endTime,"yyyy-MM-dd hh:mm:ss");
            m_alarmTimes = sdt.secsTo(edt);
        }else if(s_Col < block.startCell){
            s_Col = block.startCell;
            sdt= QDateTime::fromString(recInfo.startTime,"yyyy-MM-dd hh:mm:ss");
            edt= QDateTime::fromString(recInfo.endTime,"yyyy-MM-dd hh:mm:ss");
            m_alarmTimes = sdt.secsTo(edt);
        }else{
            continue;
        }
        break;
    }
    if(s_Col%m_smlCellNum_InbigCell==0 && s_Col != 0){
        s_Col++;
    }
    if(m_replayTimerCtl[m_rplyIndex].current_Cell !=0){
        QTableWidgetItem *now_stem = ui->playback_process_tbW->item(m_Replay_Row,m_replayTimerCtl[m_rplyIndex].current_Cell);
        now_stem->setBackground(QBrush(m_originalColBackColor));
    }

    QTableWidgetItem *original_item = ui->playback_process_tbW->item(m_Replay_Row,s_Col);
    m_originalColBackColor = original_item->backgroundColor();////stored the  original color
    original_item->setBackground(QBrush(RPLY_CUCOL_BACKCOLOR));

    m_replayTimerCtl[m_rplyIndex].current_Cell=s_Col;
    int sc=(s_Col*1.0*m_smlCell_seconds);
    int ch=sc/3600;
    int cm = (sc%3600)/60;
    int cs = (sc%3600)%60;
    char ptime[16]={'\0'};sprintf(ptime,"%04d-%02d-%02d %02d:%02d:%02d",m_reply_SelectDate.year(),m_reply_SelectDate.month(),m_reply_SelectDate.day(),ch,cm,cs);
    m_Replay_StartTime = QString(ptime);

    playback_Play(ui->ReplaySwitch_cBx1_1->currentIndex(),0);
}




void replayCenter::httpRply_slots(QString url, QJsonDocument rspData)
{
    if(url == QString("/playback/replay/guiSetup")){///Replay Ctl
            if(m_replayCtl){
                QJsonObject json= rspData.object();
                QString isSUC = json["result"].toString();
                QString Method = json["method"].toString();
                QJsonArray jsonData = json["data"].toArray();
                if(Method.contains("POST",Qt::CaseInsensitive)){
                    if(isSUC.contains("SUCCESS",Qt::CaseInsensitive)){
                          m_replayTimerCtl[m_rplyIndex].status = m_rplyStaus;
                          m_replayTimerCtl[m_rplyIndex].speed = static_cast<rplySpeed>(m_RplySpeed);
                          if(m_rplyStaus== Rply_Playing){
                              PRTLOG()<<"Playing";
                          }else{
                              m_ctrlTimer_Timing.stop();
                          }
                     }else{
                        Hint_Dlg *l= Hint_Dlg::Instance();
                        l->hint_setTitleText("错误");
                        l->hint_setHintPixmap(QPixmap("image/error.png"));
                        for(int x=0;x<jsonData.size();x++){
                            QJsonObject levelObject = jsonData[x].toObject();
                            l->hint_setHintText(levelObject["reason"].toString());
                        }
                        l->show();
                    }
                }
                if(Method.contains("QUERY",Qt::CaseInsensitive)){
                    PRTLOG()<<"Query process";
                }
                m_replayCtl=false;
            }
     }else if(url == QString("/playback/replay/setup")){
        if(m_replayRecordQuery){
                m_rplyGetResultTimes--;
                QJsonObject json= rspData.object();
                QString isSUC = json["result"].toString();
                QJsonArray jsonData = json["data"].toArray();
                int index=0;
                int ch = json["ch"].toInt();
                for(int i =0;i<MAX_REPLAY_WIN_NUM;i++){
                    if(ch ==m_RecordInfoArray[i].ch){
                        index =i;
                        break;
                    }
                }
                if(isSUC.contains("SUCCESS",Qt::CaseInsensitive)){
                    for(int x=0;x<jsonData.size();x++){
                          QJsonObject xx=jsonData[x].toObject();
                          QJsonArray recordArray;
                           REC_Type recTpe;
                           switch(x){
                            case 0:recTpe=REC_TIMING;recordArray = xx["Time"].toArray();break;
                            case 1:recTpe=REC_ALARM;recordArray = xx["Alarm"].toArray();break;
                            default:recTpe=REC_TIMING;recordArray = xx["Time"].toArray();break;
                           }
                           for(int y=0;y<recordArray.size();y++){
                               QJsonObject recordData = recordArray[y].toObject();
                               QString StartTime=recordData["StartTime"].toString().trimmed();
                               QString EndTime=recordData["EndTime"].toString().trimmed();
                               h_records record;
                               memset(&record,0,sizeof(record));
                               sprintf(record.startTime,"%s",StartTime.toLocal8Bit().data());
                               sprintf(record.endTime,"%s",EndTime.toLocal8Bit().data());
                               switch(x){
                                case 0:m_RecordInfoArray[index].timing_rTList.append(record);break;
                                case 1:m_RecordInfoArray[index].alarm_rTList.append(record);break;
                                default:m_RecordInfoArray[index].timing_rTList.append(record);break;
                               }
                           }
                      }
                }else{
                    PRTLOG()<<QString("ch_%1 not found Record").arg(m_RecordInfoArray[index].ch);
                }
                if(m_rplyGetResultTimes==0){///Query finished
                    m_rplyIndex=0;
                    m_replayRecordQuery=false;
                    replay_rePaint_CurrentData();///RepaintRowData
                }
        }
    }else if(url == QString("/userMgnt/iAmAlive")){
        if(m_rplyStaus== Rply_Playing){
            QJsonObject json= rspData.object();
            QString isSUC = json["result"].toString();
            if(isSUC.contains("SUCCESS",Qt::CaseInsensitive)){
                    ;
            }else{
                PRTLOG()<<"i am logout";
            }
        }
    }
}


void replayCenter::on_playbackCtl_SpeedAdd_pBt_clicked()
{
    if(m_replayTimerCtl[m_rplyIndex].status == Rply_Playing){
        if(m_RplySpeed < Rply_Speed_16)
            m_RplySpeed++;
        QJsonObject postData;
        postData["userID"] = QString::number(OnlineUserInfo.userID);
        postData["reqType"] = QString("POST");
        postData["channel"] = m_rply_ch;///query---Ch
        postData["outch"] = m_rply_outch;///
        postData["command"] =QString("SPEED");
        postData["speed"] =QString::number(speedInt[m_RplySpeed]);
        m_replayCtl=true;
        m_rplyStaus = Rply_Playing;
        if(m_replayTimerCtl[m_rplyIndex].status == Rply_Playing )
            emit httpReq_signal(g_httpClient.httpsEnable,g_httpClient.http_srvIP,QString("/playback/replay/guiSetup"),g_httpClient.httpPort,postData);
        ui->playbackCtl_SpeedInfo_lbl->setText(QString("x %1").arg(speedString[m_RplySpeed]));
        replay_timerRestart();

    }else{
        Hint_Dlg *l= Hint_Dlg::Instance();
        l->hint_setTitleText("错误");
        l->hint_setHintPixmap(QPixmap("image/error.png"));
        l->hint_setHintText("请先选择录像进行回放!");
        l->show();
    }
}

void replayCenter::replay_timerRestart(){
    playback_initAlarmPara();
    m_ctrlTimer_Timing.setInterval(1000);///1s
    m_ctrTimer_timeOutTimes=0;
    m_ctrlTimer_Timing.start();
}
void replayCenter::on_playbackCtl_SpeedSub_pBt_clicked()
{
    if(m_replayTimerCtl[m_rplyIndex].status == Rply_Playing){
        if(m_RplySpeed > Rply_Speed_116)
            m_RplySpeed--;
        QJsonObject postData;
        postData["userID"] = QString::number(OnlineUserInfo.userID);
        postData["reqType"] = QString("POST");
        postData["channel"] = m_rply_ch;///query---Ch
        postData["outch"] = m_rply_outch;///
        postData["command"] =QString("SPEED");
        postData["speed"] =QString::number(speedInt[m_RplySpeed]);
        m_replayCtl=true;
        m_rplyStaus = Rply_Playing;
        if(m_replayTimerCtl[m_rplyIndex].status == Rply_Playing )
            emit httpReq_signal(g_httpClient.httpsEnable,g_httpClient.http_srvIP,QString("/playback/replay/guiSetup"),g_httpClient.httpPort,postData);
        if(QString(speedInt[m_RplySpeed]) == QString("116"))
            ui->playbackCtl_SpeedInfo_lbl->setText(QString("x %1").arg("1/16"));
        else if(QString(speedInt[m_RplySpeed]) == QString("108"))
            ui->playbackCtl_SpeedInfo_lbl->setText(QString("x %1").arg("1/8"));
        else if(QString(speedInt[m_RplySpeed]) == QString("104"))
            ui->playbackCtl_SpeedInfo_lbl->setText(QString("x %1").arg("1/4"));
        else if(QString(speedInt[m_RplySpeed]) == QString("102"))
            ui->playbackCtl_SpeedInfo_lbl->setText(QString("x %1").arg("1/2"));
        else
            ui->playbackCtl_SpeedInfo_lbl->setText(QString("x %1").arg(speedString[m_RplySpeed]));

        replay_timerRestart();
    }else{
        Hint_Dlg *l= Hint_Dlg::Instance();
        l->hint_setTitleText("错误");
        l->hint_setHintPixmap(QPixmap("image/error.png"));
        l->hint_setHintText("请先选择录像进行回放!");
        l->show();
    }
}









void replayCenter::recordCellInfoCpy(QList <recordCellInfo> *dst,QList <recordCellInfo> src){
    for(int i =0;i< src.count();i++)
           dst->append(src.at(i));
}

void replayCenter::recordListInfoCpy(QList <h_records> *dst,QList <h_records> src){
    for(int i =0;i< src.count();i++)
           dst->append(src.at(i));
}


void replayCenter::on_Replay_calendarWidget_selectionChanged()
{
    replay_startQuery();
}



void replayCenter::replay_recordQuery(int ch){

    ////Clear Current color;
    for(int col=0;col<m_tbW_col;col++){
       for(int row=0;row<m_tbW_row;row++){
           QTableWidgetItem *item = ui->playback_process_tbW->item(row,col);
           if(row==0){
               item->setBackground(QBrush(ROW_HGAP_BACKCOLOR));
               item->setSelected(false);
           }else{
               if(row%2){
                   item->setBackground(QBrush(ROW_NORECORD_BACKCOLOR));
                   if(col%m_smlCellNum_InbigCell==0 && col != 0){
                       item->setBackground(QBrush(ROW_VGAP_BACKCOLOR));///
                   }
               }else{
                   item->setBackground(QBrush(ROW_HGAP_BACKCOLOR));
               }
           }
       }
    }
    this->update();
    m_replayRecordQuery=true;
    QJsonObject postData;
    postData["userID"] = QString::number(OnlineUserInfo.userID);
    postData["chanNum"] =ch;
    postData["lock"] = QString("ANY");

    m_reply_SelectDate = ui->Replay_calendarWidget->selectedDate();
    QTime start_time =QTime::fromString("00:00:00","hh:mm:ss");
    QTime end_time =QTime::fromString("23:59:59","hh:mm:ss");;
    char dt_str[64]={'\0'};
    sprintf(dt_str,"%04d-%02d-%02d %02d:%02d:%02d",m_reply_SelectDate.year(),m_reply_SelectDate.month(),m_reply_SelectDate.day(),start_time.hour(),start_time.minute(),start_time.second());
    postData["startTime"] = QString(dt_str);
    memset(dt_str,0,sizeof(dt_str));
    sprintf(dt_str,"%04d-%02d-%02d %02d:%02d:%02d",m_reply_SelectDate.year(),m_reply_SelectDate.month(),m_reply_SelectDate.day(),end_time.hour(),end_time.minute(),end_time.second());
    m_Replay_EndTime = QString(dt_str);
    postData["endTime"] = m_Replay_EndTime;
    postData["reqType"] = QString("QUERY");
    emit httpReq_signal(g_httpClient.httpsEnable,g_httpClient.http_srvIP,QString("/playback/replay/setup"),g_httpClient.httpPort,postData);
}


void replayCenter::replay_startQuery(){

    for(int i=0;i<MAX_REPLAY_WIN_NUM;i++){
        m_RecordInfoArray[i].index = i;
        m_RecordInfoArray[i].ch = -1;
        m_RecordInfoArray[i].timing_rTList.clear();
        m_RecordInfoArray[i].timing_rCList.clear();
        m_RecordInfoArray[i].alarm_rTList.clear();
        m_RecordInfoArray[i].alarm_rCList.clear();
    }
    m_rplyGetResultTimes = m_replay_totalChs;
    switch(m_replay_totalChs){
        case 1:{
            m_RecordInfoArray[0].index=0;
            m_RecordInfoArray[0].ch=ui->ReplaySwitch_cBx1_1->currentIndex();
            replay_recordQuery(m_RecordInfoArray[0].ch);
            break;
        }
        case 4:{
            for(int i=0;i<4;i++){
                m_RecordInfoArray[i].index=i;
                m_RecordInfoArray[i].ch=i;///need selected the ch from ui
                replay_recordQuery(m_RecordInfoArray[i].ch);
            }break;
        }
        case 9:{
            for(int i=0;i<9;i++){
                m_RecordInfoArray[i].index=i;
                m_RecordInfoArray[i].ch=i;///need selected the ch from ui
                replay_recordQuery(m_RecordInfoArray[i].ch);
            }break;
        }
        case 16:{
            for(int i=0;i<16;i++){
                m_RecordInfoArray[i].index=i;
                m_RecordInfoArray[i].ch=i;///need selected the ch from ui
                replay_recordQuery(m_RecordInfoArray[i].ch);
            }break;
        }
    }
}


void replayCenter::replay_rePaint_CurrentData(){
        replay_rePaint_ByRECType(REC_TIMING);
        replay_rePaint_ByRECType(REC_ALARM);
        this->update();
}

void replayCenter::on_playbackCtl_Start_pBt_clicked()
{
    if(m_RecordInfoArray[m_rplyIndex].timing_rCList.count()!=0)
        replay_selectTimeToReplay(m_replayTimerCtl[m_rplyIndex].current_Cell);
    else{
        Hint_Dlg *l= Hint_Dlg::Instance();
        l->hint_setTitleText("错误");
        l->hint_setHintPixmap(QPixmap("image/error.png"));
        l->hint_setHintText("未查询到有效录像!");
        l->show();
    }
}

void replayCenter::on_playbackCtl_Stop_pBt_clicked()
{
    if(m_replayTimerCtl[m_rplyIndex].status == Rply_Playing)
        playback_stop();
    else{
        Hint_Dlg *l= Hint_Dlg::Instance();
        l->hint_setTitleText("错误");
        l->hint_setHintPixmap(QPixmap("image/error.png"));
        l->hint_setHintText("请先选择录像进行回放");
        l->show();
    }
}
void replayCenter::on_ReplaySwitch_cBx1_1_currentIndexChanged(int index)
{
    Q_UNUSED(index);
    replay_startQuery();
}

void replayCenter::on_recordType_cBx_currentIndexChanged(const QString &arg1)
{
   replay_startQuery();
}
void replayCenter::on_playbackCtl_Date_pBt_clicked()
{
    if(ui->ReplaySearch_From->isHidden()){
        ui->ReplaySearch_From->show();
    }else{
        ui->ReplaySearch_From->hide();
    }
}

void replayCenter::replay_queryProcess(){
    QJsonObject postData;
    postData["userID"] = QString::number(OnlineUserInfo.userID);
    postData["reqType"] = QString("QUERY");
    postData["channel"] = m_rply_ch;///query---Ch
    postData["outch"] = m_rply_outch;///;
    m_replayCtl=true;
    m_rplyStaus = Rply_Playing;
    emit httpReq_signal(g_httpClient.httpsEnable,g_httpClient.http_srvIP,QString("/playback/replay/guiSetup"),g_httpClient.httpPort,postData);

    emit httpReq_signal(g_httpClient.httpsEnable,g_httpClient.http_srvIP,QString("/playback/replay/setup"),g_httpClient.httpPort,postData);
}
void replayCenter::replay_IamAlive(){
    QJsonObject postData;
    postData["userID"] = QString::number(OnlineUserInfo.userID);
    postData["reqType"] = QString("QUERY");
    if(m_rplyStaus == Rply_Playing)
        emit httpReq_signal(g_httpClient.httpsEnable,g_httpClient.http_srvIP,QString("/userMgnt/iAmAlive"),g_httpClient.httpPort,postData);
}

void replayCenter::playback_initAlarmPara(){
    switch(m_RplySpeed){
        case Rply_Speed_116:m_alarmSpeed =16;m_alarmStep=1;break;
        case Rply_Speed_108:m_alarmSpeed =8;m_alarmStep=1;break;
        case Rply_Speed_104:m_alarmSpeed =4;m_alarmStep=1;break;
        case Rply_Speed_102:m_alarmSpeed =2;m_alarmStep=1;break;
        case Rply_Speed_1:m_alarmSpeed =1;m_alarmStep=1;break;
        case Rply_Speed_2:m_alarmSpeed =1;m_alarmStep=2;break;
        case Rply_Speed_4:m_alarmSpeed =1;m_alarmStep=4;break;
        case Rply_Speed_8:m_alarmSpeed =1;m_alarmStep=8;break;
        case Rply_Speed_16:m_alarmSpeed =1;m_alarmStep=16;break;
    }
}
void replayCenter::rply_processNotifyTcp_slot(){
   QTcpSocket *cli=nullptr;
   cli=m_rplyProcessTcpSrv->nextPendingConnection();
   if(cli != 0){
       m_client_sock = cli;
       connect(m_client_sock,SIGNAL(readyRead()),this,SLOT(rply_TcpRecv_slot()));
   }
}

void replayCenter::rply_TcpRecv_slot(){
    QByteArray pck=m_client_sock->readAll();
    QJsonDocument pack=QJsonDocument::fromJson(pck);
    QJsonObject pack_json= pack.object();
    int screen,outch;
    QString StartTime,EndTime;
    screen = pack_json["screen"].toInt();
    outch = pack_json["outch"].toInt();
    StartTime = pack_json["StartTime"].toString().trimmed();
    EndTime = pack_json["EndTime"].toString().trimmed();
    QDateTime ct = QDateTime::fromString(StartTime,"yyyy-MM-dd hh:mm:ss");
    int tme=QTime(0,0,0,0).secsTo(ct.time());
    m_replayTimerCtl[outch].current_Cell = static_cast<int>(tme/m_smlCell_seconds);
    m_client_sock->close();
}

void replayCenter::on_Replay_Close_tBt_clicked()
{
    this->close();
}
